package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传
     */
    @PostMapping
    public AjaxResult upload(@RequestPart MultipartFile file) throws IOException {
        //获取字节数组
        byte[] bytes = file.getBytes();
        //获取原始文件名
        String oName = file.getOriginalFilename();
        //使用字符串分割，获取到文件的后缀，不要那个点
        String extName = oName.substring(oName.indexOf(".") + 1);
        //调用工具类上传文件，并返回
        String fastName = FastDfsUtils.upload(bytes, extName);
        //响应给前端
        return AjaxResult.me().setResultObj(fastName);
    }

    /**
     * 删除文件
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){
        //path = /group1/M00/04/72/CgAIC2QesbyABs3mAAJXkeNsGkk421.jpg
        //使用字符串分割获取到第一个斜杠后面的：group1/M00/04/72/CgAIC2QesbyABs3mAAJXkeNsGkk421.jpg
        String pathTmp = path.substring(1);
        //截取下标0到下一个斜杠的数据就是我们的groupName：group1
        String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
        //再截取斜杠后面的数据就是fileName：M00/04/72/CgAIC2QesbyABs3mAAJXkeNsGkk421.jpg
        String fileName = pathTmp.substring(pathTmp.indexOf("/") + 1);
        FastDfsUtils.delete(groupName,fileName);
        return new AjaxResult();
    }
}
